<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

function invoice_list_page()
{
    @$output = drupal_render(drupal_get_form('invoice_list_form'));
    return $output;
}

function invoice_list_form($form, &$form_state)
{
    global $user;
    if (!empty($_GET['distributor_id'])) {
        $form_state['distributor_id'] = $_GET['distributor_id'];
    }
    if (empty($form_state['distributor_id'])) {
        $form['address_distributor_markup']['#markup'] = '<div class="address-distributor-search">';
        $form['address_distributor'] = _insert_address_distributor_selection_form($form, $form_state, 'address_distributor');
        $form['address_distributor_markup_close']['#markup'] = '</div>';
    } else {
        $form['#distributor_id'] = $form_state['distributor_id'];
        $res = get_info($form['#distributor_id'], 'distributor');
        $form['#distributor_name'] = $res[0]->distributor_name;
//        $addr_red = get_all_addrname($res[0]->addr_id);
//        $province = $addr_red[0]->province?$addr_red[0]->province:"";
//        $city = $addr_red[0]->city? '  '.$addr_red[0]->city:"";
//        $county = $addr_red[0]->county? '  '.$addr_red[0]->county:"";
//        $town = $addr_red[0]->town? '  '.$addr_red[0]->town:"";
//        $village = $addr_red[0]->village? '  '.$addr_red[0]->village:"";
//        $form['#farmer_addr'] =$province.$city.$county.$town.$village;
    }
    $form['sacfvariety'] = _insert_sacfvariety_selection_form(!empty($form_state['values']['sacfvariety']) ? $form_state['values']['sacfvariety'] : '');

    _insert_sales_type_selection_form($form, !empty($form_state['values']['sales_type']) ? $form_state['values']['sales_type'] : '');
    $fields = array(
        '' => '请选择',
        'quantity' => '数量',
    );
    numerical_range_search($form, $fields);
    $inorout = array('' => '请选择', '关内' => '关内', '关外' => '关外');
    $form['inorout'] = array(
        '#type' => 'select',
        '#options' => $inorout
    );
    $init_year = !empty($form_state['values']['year']) ? $form_state['values']['year'] : "";
    $init_month = !empty($form_state['values']['month']) ? $form_state['values']['month'] : "";
    _insert_date_selection_form($form, $form_state, 5, $init_year, $init_month);
//    $form['invoice_date'] = array(
//        '#type' => 'date',
//        '#default_value' =>  _date_db_2_form(!empty($record) ? $record->invoice_date : ''),
//    );
    if (get_user_role_name($user->uid) === 'administrator') {

    } else {
        $form['employee_list'] = _insert_loginuser_choose_salesman_selection($user);
    }
    $table['#markup'] = data_list_view_page($form, $form_state);
    ajax_submit_form($form, $form_state, $table, '');

    return $form;
}

function invoice_list_form_validate($form, &$form_state)
{
}

function data_list_view_page($form = '', &$form_state = '')
{
    global $user;
    $user_info = _get_user_info($user->uid);
    //表头
    $header = array(
        array('data' => '选择', 'class' => ['essential no']),
        array('data' => '发票id号', 'class' => ['integrant essential break invoice_id'], 'field' => 'invoice_id'),
        array('data' => '日期', 'class' => ['integrant essential date'], 'field' => 'invoice_date'),
        array('data' => '销售员', 'class' => ['essential salesman']),
        isset($form_state['distributor_id']) && !empty($form_state['distributor_id']) ? "" :
            array('data' => '经销商', 'class' => ['essential distributor']),
        array('data' => '销售类型', 'class' => ['essential sales_type_name']),
        array('data' => '化肥品种', 'class' => ['essential sacfvariety']),
        array('data' => '配比', 'class' => 'optional proportion'),
        array('data' => 'SM', 'class' => 'optional SM'),
        array('data' => '数量', 'class' => ['essential quantity'], 'field' => 'quantity'),
        array('data' => '火车站名', 'class' => ['optional station_name']),
        array('data' => '关内/关外', 'class' => ['optional inorout'], 'field' => 'inorout'),
        array('data' => '操作', 'class' => ['essential more']),

    );
    $output = '';
    $query = db_select('invoice', 'I')->extend('PagerDefault')->extend('TableSort');
    $query->leftjoin('employee', 'E', 'E.employee_id=I.salesman_id');
    $query->leftjoin('distributor', 'D', 'D.distributor_id=I.distributor_id');
    $query->leftjoin('sales_type', 'ST', 'ST.sales_type_id=I.sales_type_id');
    $query->leftjoin('product_sku', 'SV', 'SV.product_sku_id=I.sacfvariety_id');

    $query->fields('I');

    $query->addField('D', 'distributor_name');
    $query->addField('E', 'employee_name', 'salesman');
    $query->addField('ST', 'sales_type_name');
    $query->addField('SV', 'variety_name');
    $query->addField('SV', 'proportion');
    $query->addField('SV', 'SM');
    $query->join('addr', 'da', 'da.addr_id=D.addr_id');
    $query->leftJoin('addr', 'A', 'A.addr_id=I.delivery_addr_id');
    $query->leftJoin('addr', 'A1', 'A.province_id=A1.addr_id');
    $query->leftJoin('addr', 'A2', 'A.city_id=A2.addr_id');
    $query->leftJoin('addr', 'A3', 'A.county_id=A3.addr_id');
    if (!empty($form_state['values']['county'])) {//县级
        $query->condition('da.county_id', $form_state['values']['county'], '=');
    } elseif (!empty($form_state['values']['city'])) {//市级
        $query->condition('da.city_id', $form_state['values']['city'], '=');
    } elseif (!empty($form_state['values']['province'])) {//省级
        $query->condition('da.province_id', $form_state['values']['province'], '=');
    }

    if (!empty($form_state['values']['sacfvariety'])) {
        if ($form_state['values']['sacfvariety']) {
            $query->condition('I.sacfvariety_id', $form_state['values']['sacfvariety'], '=');
        }

    }
    if (!empty($form_state['values']['sales_type'])) {
        if ($form_state['values']['sales_type']) {
            $query->condition('I.sales_type_id', $form_state['values']['sales_type'], '=');
        }
    }
    if (!empty($form_state['values']['distributor'])) {//查询条件
        if ($form_state['values']['distributor']) {
            $query->condition('D.distributor_name', '%'.db_like($form_state['values']['distributor']).'%', 'LIKE');
        }
    }
    $datestr = '';
    if (!empty($form_state['values']['year'])) {//查询条件
        if ($form_state['values']['year']) {
            $datestr .= $form_state['values']['year'] . '-';
        }
    }
    if (!empty($form_state['values']['month'])) {//查询条件
        if ($month = $form_state['values']['month']) {
            if ($month < 10)
                $datestr .= '0' . $form_state['values']['month'];
            else
                $datestr .= $form_state['values']['month'];
        }
    }
    if ($datestr) {
        $query->condition('I.invoice_date', db_like($datestr) . '%', 'LIKE');
    }

    $query->addField('A1', 'name', 'province');
    $query->addField('A2', 'name', 'city');
    $query->addField('A3', 'name', 'county');

    salesman_distributor_role_relate_query_info($form_state,$query,'view all invoice','view own invoice','I');

    if (!empty($form_state['values']['employee_list']) && $form_state['values']['employee_list'] != "default") {//查询条件
        if ($form_state['values']['employee_list']) {
            $query->condition('I.salesman_id', $form_state['values']['employee_list']);
        }
    }

    if (empty($form_state['values']) || empty($form_state['values']['order'])) {
        $query->orderBy('I.timestamp', 'DESC');
    }

    if (!empty($form_state['values']['field'])) {
        if (!empty($form_state['values']['min_number']) && !empty($form_state['values']['max_number'])) {
            $db_and = db_and();
            $db_and->condition('I.' . $form_state['values']['field'], $form_state['values']['min_number'], '>');
            $db_and->condition('I.' . $form_state['values']['field'], $form_state['values']['max_number'], '<');
            $query->condition($db_and);
        } elseif (!empty($form_state['values']['min_number'])) {
            $query->condition('I.' . $form_state['values']['field'], $form_state['values']['min_number'], '>');
        } elseif (!empty($form_state['values']['max_number'])) {
            $query->condition('I.' . $form_state['values']['field'], $form_state['values']['max_number'], '<');
        }
    }
    if (!empty($form_state['distributor_id'])) {
        $query->condition('D.distributor_id', $form_state['distributor_id']);
    }

    if (!empty($form_state['values']['inorout'])) {
        $query->condition('I.inorout', $form_state['values']['inorout'], '=');
    }
    if (!empty($form_state['values']['invoice_date'])) {
        $query->condition('I.invoice_date', _date_form_2_db($form_state['values']['invoice_date']), '=');
    }
    $query->limit(variable_get("list_page_item_number", 5));
    $invoiceInfo = $query->orderByHeader($header)->execute();

    $rows = array();
    //表内容
    $n = 1;
    foreach ($invoiceInfo as $row) {
        if (nonghua_user_access('invoice', 'delete', $row->id, $row->author_uid, 0)) {
            $disabled = ' class="listViewTableCheck" ';
        } else {
            $disabled = ' disabled="true" ';
        }
        $rows[] = array(
            array('data' => '<input type="checkbox"' . $disabled . ' value ="' . $row->id . '"/>' . $n++, 'class' => ['integrant essential no']),
            array('data' => $row->invoice_id, 'class' => ['integrant essential break invoice_id']),
            array('data' => $row->invoice_date, 'class' => ['integrant goRight essential date']),
            array('data' => $row->salesman, 'class' => ['essential salesman']),//
            isset($form_state['distributor_id']) && !empty($form_state['distributor_id']) ? "" :
                array('data' => '<a href="' . base_path() . 'distributor/edit/' . $row->distributor_id . '?distributor_id=' . $row->distributor_id . '" data-toggle="modal" target = "_self">' . $row->distributor_name . "</a>", 'class' => ['integrant haveTobr essential distributor']),
            array('data' => $row->sales_type_name, 'class' => ['essential sales_type_name']),
            array('data' => $row->variety_name, 'class' => ['integrant goRight essential sacfvariety']),
            array('data' => $row->proportion, 'class' => 'optional proportion'),
            array('data' => $row->SM, 'class' => 'optional SM'),
            array('data' => $row->quantity, 'class' => ['essential quantity']),
            array('data' => $row->station_name, 'class' => ['optional station_name']),
            array('data' => $row->inorout, 'class' => ['optional inorout']),
            isset($form_state['distributor_id']) && !empty($form_state['distributor_id']) ?
                array('data' => '<a href="' . base_path() . 'sales/invoice/edit/' . $row->id . '?distributor_id=' . $form_state['distributor_id'] . '" data-toggle="modal" target = "_top"><img width="20px" height="20px" src="' . base_path() . 'sites/all/themes/tweme/images/images/cz.png"/></a>', 'class' => 'essential more') :
                array('data' => '<a href="' . base_path() . 'sales/invoice/edit/' . $row->id . '" data-toggle="modal" target = "_top"><img width="20px" height="20px" src="' . base_path() . 'sites/all/themes/tweme/images/images/cz.png"/></a>', 'class' => 'essential more'),
        );
    }


    $output .= theme('table', array('header' => $header, 'rows' => $rows, 'empty' => t('没有记录'), 'attributes' => array('class' => array('table table-bordered table-striped table-hover enhanced')))); //表格
    /*	 * *按钮** */
    if (sizeof($rows) > 0 && (user_access('delete own invoice') || user_access('delete all invoice'))) {
        $output .= '<a href="javascript:void(0)" id="listViewTableSelectAll" data-toggle="modal" class="btn btn-mini">全选</a>';
        $output .= '<a href="javascript:void(0)" id="listViewTableDeleteSelected" data-toggle="modal" class="btn btn-mini">删除所选</a>';
    }
    $output .= '<a href="'.base_path().'sales/invoice/export?distributor='.$form_state['valuse']['distributor'].'&sacfvariety='.$form_state['values']['sacfvariety'].'&year='.$form_state['values']['year'].'&month='.$form_state['values']['month'].'&sales_type='.$form_state['values']['sales_type'].'&inorout='.$form_state['valuse']['inorout'].'&field='.$form_state['values']['field'].'&min_number='.$form_state['values']['min_number'].'&max_number='.$form_state['values']['max_number'].'" data-toggle="modal" class="btn btn-mini">导出</a>';

    $output .= theme('pager');
    return $output;
}

function invoice_delete()
{
    ajax_table_delete('invoice', 'id');
}

function invoice_export($form,&$form_state){
    $letter = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
    $tableheader = array('经销商','销售员','销售类型','发票ID','日期','数量','到站地名','路局','关内/关外','到站地址','化肥品种');
    $data = get_invoice_data($form, $form_state);
    nonghua_php_excel($letter,$tableheader,$data,'销售数据');
}

function get_invoice_data($form = '', &$form_state = ''){
    global $user;
    $user_info = _get_user_info($user->uid);
    $query = db_select('invoice', 'I');
    $query->leftjoin('employee', 'E', 'E.employee_id=I.salesman_id');
    $query->leftjoin('distributor', 'D', 'D.distributor_id=I.distributor_id');
    $query->leftjoin('sales_type', 'ST', 'ST.sales_type_id=I.sales_type_id');
    $query->leftjoin('product_sku', 'SV', 'SV.product_sku_id=I.sacfvariety_id');
    $query->join('addr', 'da', 'da.addr_id=D.addr_id');
    $query->leftJoin('addr', 'A', 'A.addr_id=I.delivery_addr_id');
    $query->leftJoin('addr', 'A1', 'A.province_id=A1.addr_id');
    $query->leftJoin('addr', 'A2', 'A.city_id=A2.addr_id');
    $query->leftJoin('addr', 'A3', 'A.county_id=A3.addr_id');
    if (!empty($form_state['values']['county'])) {//县级
        $query->condition('da.county_id', $form_state['values']['county'], '=');
    } elseif (!empty($_GET['city'])) {//市级
        $query->condition('da.city_id', $form_state['values']['city'], '=');
    } elseif (!empty($_GET['province'])) {//省级
        $query->condition('da.province_id', $_GET['province'], '=');
    }

    if (!empty($_GET['sacfvariety'])) {
        if ($_GET['sacfvariety']) {
            $query->condition('I.sacfvariety_id', $_GET['sacfvariety'], '=');
        }

    }
    if (!empty($_GET['sales_type'])) {
        if ($_GET['sales_type']) {
            $query->condition('I.sales_type_id', $_GET['sales_type'], '=');
        }
    }
    if (!empty($_GET['distributor'])) {//查询条件
        if ($_GET['distributor']) {
            $query->condition('D.distributor_name', '%'.db_like($_GET['distributor']).'%', 'LIKE');
        }
    }
    $datestr = '';
    if (!empty($_GET['year'])) {//查询条件
        if ($_GET['year']) {
            $datestr .= $_GET['year'] . '-';
        }
    }
    if (!empty($_GET['month'])) {//查询条件
        if ($month = $_GET['month']) {
            if ($month < 10)
                $datestr .= '0' .$_GET['month'];
            else
                $datestr .= $_GET['month'];
        }
    }
    if ($datestr) {
        $query->condition('I.invoice_date', db_like($datestr) . '%', 'LIKE');
    }
    $query->addField('D', 'distributor_name');
    $query->addField('E', 'employee_name', 'salesman');
    $query->addField('ST', 'sales_type_name');
    $query->fields('I',array('invoice_id','invoice_date','quantity','station_name','railway_bureau','inorout'));
    $query->addField('A1', 'name', 'province');
    $query->addField('A2', 'name', 'city');
    $query->addField('A3', 'name', 'county');
    $query->addField('SV', 'variety_name');
    $query->addField('SV', 'proportion');
    $query->addField('SV', 'SM');

    salesman_distributor_role_relate_query_info($form_state,$query,'view all invoice','view own invoice','I');

    if (!empty($_GET['employee_list']) && $_GET['employee_list'] != "default") {//查询条件
        if ($form_state['values']['employee_list']) {
            $query->condition('I.salesman_id', $_GET['employee_list']);
        }
    }

    if (empty($form_state['values'])) {
        $query->orderBy('I.timestamp', 'DESC');
    }

    if (!empty($_GET['field'])) {
        if (!empty($_GET['min_number']) && !empty($_GET['max_number'])) {
            $db_and = db_and();
            $db_and->condition('I.' . $_GET['field'],$_GET['min_number'], '>');
            $db_and->condition('I.' . $_GET['field'],$_GET['max_number'], '<');
            $query->condition($db_and);
        } elseif (!empty($_GET['min_number'])) {
            $query->condition('I.' . $_GET['field'], $_GET['min_number'], '>');
        } elseif (!empty($_GET['max_number'])) {
            $query->condition('I.' . $_GET['field'], $_GET['max_number'], '<');
        }
    }
    if (!empty($form_state['distributor_id'])) {
        $query->condition('D.distributor_id', $form_state['distributor_id']);
    }

    if (!empty($_GET['inorout'])) {
        $query->condition('I.inorout', $_GET['inorout'], '=');
    }
    if (!empty($_GET['invoice_date'])) {
        $query->condition('I.invoice_date', _date_form_2_db($_GET['invoice_date']), '=');
    }
    $invoiceInfo = $query->execute()->fetchAll();
    foreach($invoiceInfo as $k => $v){
        $invoiceInfo[$k]->province= $v->province.$v->city.$v->county;
        unset($invoiceInfo[$k]->city);
        unset($invoiceInfo[$k]->county);
        $invoiceInfo[$k]->variety_name = $v->variety_name.$v->proportion.$v->SM;
        unset($invoiceInfo[$k]->proportion);
        unset($invoiceInfo[$k]->SM);
    }
    return $invoiceInfo;
}
